#include "SensorPlotHandlerDialog.h"
#include "ui_SensorPlotHandlerDialog.h"
#include <boost/filesystem.hpp>
#include <QMessageBox>
#include <QStatusBar>

SensorPlotHandlerDialog::SensorPlotHandlerDialog(QWidget* parent) :
    QDialog(parent),
    ui(new Ui::SensorPlotHandlerDialog),
    plotWidget(new PlotWidget()),
    signalMapper(new QSignalMapper(this))
{
    ui->setupUi(this);

    ui->layout->addWidget(plotWidget);

    connect(signalMapper, SIGNAL(mapped(const QString &)), this, SLOT(handleMotion(const QString &)));

    statusBar = new QStatusBar;
    ui->layout->addWidget(statusBar);
    connect(plotWidget, SIGNAL(showMessage(const std::string &)), this, SLOT(showMessage(const std::string &)));
    connect(plotWidget, SIGNAL(openMotions(MMM::MotionList)), this, SIGNAL(openMotions(MMM::MotionList)));
    connect(plotWidget, SIGNAL(jumpTo(float)), this, SIGNAL(jumpTo(float)));}

SensorPlotHandlerDialog::~SensorPlotHandlerDialog() {
    delete ui;
}

void SensorPlotHandlerDialog::loadMotions(MMM::MotionList motions) {
    plotWidget->loadMotions(motions);
}

void SensorPlotHandlerDialog::addImportMotionHandler(MMM::MotionHandlerPtr motionHandler) {
    QPushButton* button = new QPushButton(QString::fromStdString(motionHandler->getDescription()));
    connect(button, SIGNAL(pressed()), signalMapper, SLOT(map()));
    signalMapper->setMapping(button, QString::fromStdString(motionHandler->getName()));
    connect(motionHandler.get(), SIGNAL(openMotions(MMM::MotionList)), this, SLOT(loadMotions(MMM::MotionList)));
    importMotionHandler[motionHandler->getName()] = motionHandler;
    plotWidget->addImportButton(button);
}

void SensorPlotHandlerDialog::handleMotion(const QString &name) {
    MMM::MotionList motions;
    importMotionHandler[name.toStdString()]->handleMotion(motions);
}

void SensorPlotHandlerDialog::showMessage(const std::string &message) {
    statusBar->showMessage(QString::fromStdString(message), 10000);
}

PlotWidget* SensorPlotHandlerDialog::getPlotWidget() {
    return plotWidget;
}

void SensorPlotHandlerDialog::moveSlider(float timestep) {
    plotWidget->moveSlider(timestep);
}
